﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;

namespace Infrastructure
{
    public class DataTableConverter
    {
        /// <summary>
        /// This method is used to construct the list of objects from relational data source.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The data source from database</param>
        /// <returns>List of objects wrapped from relational source</returns>
        public static List<T> ConvertTable2Object<T>(DataTable source)
        {
            List<T> results = new List<T>();
            Type tType = typeof(T);
            BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.GetProperty;
            foreach (DataRow row in source.Rows)
            {
                T target = Activator.CreateInstance<T>();
                foreach (DataColumn column in source.Columns)
                {
                    string columnName = column.ColumnName;
                    //get the value from source
                    object value = row[columnName];
                    if (value is DBNull)
                        continue;
                    PropertyInfo p = tType.GetProperty(columnName, flags);
                    if (p != null)
                    {
                        MethodInfo set = p.GetSetMethod();
                        if (set != null)
                        {
                            set.Invoke(target, new object[] { value });
                        }
                    }
                }
                results.Add(target);
            }
            return results;
        }

    }
}
